import os
import platform
import subprocess
from tqdm import tqdm
from .base import Tool

def get_system_info() -> dict:
    """获取系统环境信息"""
    info = {
        "os": platform.system().lower(),
        "shell": None,
        "shell_type": None
    }
    
    if info["os"] == "windows":
        # 检测是PowerShell还是CMD
        try:
            subprocess.run(["powershell", "-Command", "echo $PSVersionTable"], 
                         capture_output=True, 
                         text=True,
                         encoding='gbk')
            info["shell"] = "powershell"
            info["shell_type"] = "powershell"
        except:
            info["shell"] = "cmd"
            info["shell_type"] = "cmd"
    else:
        # Unix-like系统
        shell = os.environ.get("SHELL", "")
        info["shell"] = shell
        if "bash" in shell:
            info["shell_type"] = "bash"
        elif "zsh" in shell:
            info["shell_type"] = "zsh"
        else:
            info["shell_type"] = "sh"
    
    return info

SYSTEM_INFO = get_system_info()

def execute(params: dict) -> str:
    """执行execute_command工具"""
    with tqdm(total=100, desc="执行 execute_command", ncols=100) as pbar:
        try:
            command = params.get("command")
            if not command:
                return "错误：未提供命令"
            
            pbar.update(10)
            
            # 如果是URL，使用系统默认浏览器打开
            if ("http://" in command or "https://" in command) and SYSTEM_INFO["os"] == "windows":
                url = command.split()[-1].strip('"')  # 获取URL部分
                if '"' not in url:  # 如果URL没有被引号包围
                    url = f'"{url}"'
                command = f'explorer {url}'
            
            # 构建命令参数 - 始终使用CMD
            if SYSTEM_INFO["os"] == "windows":
                args = ["cmd", "/c", command]
            else:
                args = command.split()
            
            pbar.update(20)
            
            # 执行命令
            result = subprocess.run(
                args,
                capture_output=True,
                text=True,
                encoding='gbk' if SYSTEM_INFO["os"] == "windows" else 'utf-8'
            )
            
            pbar.update(70)
            
            # 构造返回结果
            output = []
            if result.stdout:
                output.append(f"标准输出：\n{result.stdout}")
            if result.stderr:
                output.append(f"错误输出：\n{result.stderr}")
            if result.returncode != 0:
                output.append(f"退出码：{result.returncode}")
            
            return "\n".join(output) if output else "命令执行成功，无输出"
            
        except Exception as e:
            return f"执行命令时出错：{str(e)}"

TOOL = Tool(
    name="execute_command",
    description=f"执行系统命令（当前环境：{SYSTEM_INFO['os']}, Shell类型：{SYSTEM_INFO['shell_type']}）",
    parameters={
        "command": {
            "type": "string",
            "description": "要执行的命令",
            "required": True
        }
    },
    example='''<execute_command>
<command>dir</command>
</execute_command>

# 打开URL示例：
<execute_command>
<command>explorer "https://www.baidu.com"</command>
</execute_command>''',
    execute_func=execute
)